# encoding: utf-8

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
import logging
import optparse
import os

from . import parser
from .backend import html5 as html5_backend
from .backend import latex as latex_backend

def main(argv):
    #TODO: Use argparse instead of optparse
    arg_parser = optparse.OptionParser(
            usage='Usage: %prog [options] [input_file]',
            description='Gravy markup parser.',
            version='Gravy v0.1')
    arg_parser.add_option('-f', '--format', type='choice',
            choices=['html5', 'latex'],
            help='specify output format')
    arg_parser.add_option('-o', metavar='FILE',
            help='specify output file')
    arg_parser.add_option('-q', '--quiet', action='store_true', default=False,
            help='disable warnings for malformed input')
    (options, args) = arg_parser.parse_args(argv)
    #TODO: Handle standard input if no file specified.
    if len(args) > 2:
        print('{0}: error: too many arguments'.format(
                os.path.basename(argv[0])))
        return -1
    elif len(args) < 2:
        print('{0}: error: no input file'.format(
                os.path.basename(argv[0])))
        return -1

    if not options.quiet:
        log_format = '{0}: %(levelname)s: %(message)s'.format(args[1])
        logger = logging.getLogger()
        log_handler = logging.StreamHandler()
        log_formatter = logging.Formatter(log_format)
        log_handler.setFormatter(log_formatter)
        logger.addHandler(log_handler)

    with io.open(args[1], 'r', encoding='utf-8') as input_file:
        dom = parser.parse(input_file)

    with io.open(options.o, 'w', encoding='utf-8') as output_file:
        if options.format == 'html5':
            #TODO: Wrap the backend output in a template.
            output_file.write(html5_backend.convert(dom))
        if options.format == 'latex':
            #TODO: Wrap the backend output in a template.
            output_file.write(latex_backend.convert(dom))

    return 0

